import express from "express";
import fs from "fs";
import path from "path";

// 获取当前文件的目录
const __dirname = path.dirname(new URL(import.meta.url).pathname);

const app = express();
const PORT = 3000;

// 加载书籍数据
const booksFilePath = path.join(process.cwd(), "peoject", "data", "books.json");
const books = JSON.parse(fs.readFileSync(booksFilePath, "utf-8"));

// 启用 JSON 格式请求体解析
app.use(express.json());

// 搜索书籍接口
app.get("/api/books", (req, res) => {
    const query = req.query.query?.toLowerCase().trim();

    if (!query) {
        return res.status(400).json({ message: "请提供有效的搜索关键字。" });
    }

    const results = books.filter(
        (book) =>
            book.title.toLowerCase().includes(query) ||
            book.author.toLowerCase().includes(query)
    );

    res.json(results);
});

// 启动服务器
app.listen(PORT, () => {
    console.log(`服务器已启动：http://localhost:${PORT}`);
});
